package com.qianfeng.xinyihezi.xinyihezi.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.qianfeng.xinyihezi.xinyihezi.R;
import com.qianfeng.xinyihezi.xinyihezi.adapter.GoodsGridViewAdapter;
import com.qianfeng.xinyihezi.xinyihezi.config.NetConfig;
import com.qianfeng.xinyihezi.xinyihezi.config.RetrofitInterface;
import com.qianfeng.xinyihezi.xinyihezi.customview.DrawableEditText;
import com.qianfeng.xinyihezi.xinyihezi.customview.RangeSeekBar;
import com.qianfeng.xinyihezi.xinyihezi.jsondecode.DecodeGoodsBase;
import com.qianfeng.xinyihezi.xinyihezi.model.GoodsData;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class GoodsScreenActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG = getClass().getSimpleName();
    private Retrofit mRetrofit;
    private RetrofitInterface mRetrofitInterface;
    private DecodeGoodsBase mDecodeGoodsBase;
    private DrawableEditText mEditeTextSearchGift;
    private TextView mTvCancel;
    public static Handler handler;
    private TextView tvSynthesis, tvPrice, tvHot, tvNew, tvScreen;
    private ImageView imgPriceSort, imgScreen;
    private View viewHot1, viewHot2, viewHot3, viewHot4, viewHot5;
    private View[] views = new View[]{viewHot1, viewHot2, viewHot3, viewHot4, viewHot5};
    private GridView mGridView;
    private GoodsGridViewAdapter gridViewAdapter;
    private List<GoodsData> goodsDataList;

    private int category;//商品类别
    private int pager = 1;//页数
    private int free_postage = 0;//是否包邮
    private int is_stock = 0;//是否是本省
    private int filter_type = 0;//筛选类型
    private int min_price = 0;//最低价格
    private int max_price = -1;//最高价格

    private boolean isLow2Height = false;
    private List<GoodsData> goodsDatas;
    private boolean isLastPager;
    private PopupWindow popupWindow;
    private ImageView imgIsFreePost;
    private ImageView imgIsCurrHaveGoods;
    private RangeSeekBar rangeSeekBar;
    private Button btnOver;
    private boolean isFreePost;
    private boolean isCurrHaveGoods;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_goods_screen);
        Intent intent = getIntent();
        category = intent.getIntExtra("category", 616);
        initView();
        initData();
        initPopuWindow();
        loadData();
        setListener();
    }

    /**
     * 设置监听事件//
     */
    private void setListener() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                try {
                    mRetrofitInterface.getSearchData(URLEncoder.encode(mEditeTextSearchGift.getText().toString(), "utf-8")).enqueue(new retrofit2.Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            if (response.isSuccessful()) {
                                try {
                                    toastShow(response.body().string());
                                    decodeData(response);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        };
        mGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_IDLE && isLastPager) {
                    pager++;
                    loadData();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                isLastPager = firstVisibleItem + visibleItemCount == totalItemCount;
            }
        });
        rangeSeekBar.setOnRangeChangedListener(new RangeSeekBar.OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float min, float max) {
                int minP = (int) min;
                int maxP = (int) max;
                switch (minP) {
                    case 0:
                        min_price = 0;
                        break;
                    case 20:
                        min_price = 100;
                        break;
                    case 40:
                        min_price = 300;
                        break;
                    case 60:
                        min_price = 500;
                        break;
                    case 80:
                    case 100:
                        min_price = 1000;
                        break;
                }
                switch (maxP) {
                    case 0:
                        max_price = 0;
                        break;
                    case 20:
                        max_price = 100;
                        break;
                    case 40:
                        max_price = 300;
                        break;
                    case 60:
                        max_price = 500;
                        break;
                    case 80:
                        max_price = 1000;
                        break;
                    case 100:
                        max_price = -1;
                        break;
                }
            }
        });

        gridViewAdapter.setIBackCall(new GoodsGridViewAdapter.IBackcallData() {
            @Override
            public void backGoods(View view) {
                GoodsData goodsData = (GoodsData) view.getTag();
                Intent intent = new Intent(GoodsScreenActivity.this, DetailActivity.class);
                intent.putExtra("goodsData", goodsData);
                startActivity(intent);
            }
        });
    }

    /**
     * 加载商品列表数据
     *
     * @param category     分类Id 区分商品类型
     * @param pager        可以进行分页操作
     * @param free_postage 是否包邮 0不包邮 1包邮  默认0
     * @param is_stock     是否本省发货 0不是  1本省发货  默认0
     * @param filter_type  过滤类型  综合排序0   价格低到高1  价格高到低2  热度3   最新4
     * @param min_price    最低价格0
     * @param max_price    最高价格  -1为不限制  默认-1
     */
    private void loadBaseData(int category, int pager, int free_postage, int is_stock, int filter_type, int min_price, int max_price) {
        mRetrofitInterface.getGoodsShowJson(category, pager, free_postage, is_stock, filter_type, min_price, max_price).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    try {
                        decodeData(response);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    /**
     * 解析数据
     */
    private void decodeData(Response<ResponseBody> response) throws IOException {
        String resultJson = response.body().string();
        goodsDatas = mDecodeGoodsBase.decodeGoodsBase(resultJson);
        goodsDataList.addAll(goodsDatas);
        goodsDatas.clear();
        gridViewAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        goodsDataList = new ArrayList<>();
        mRetrofit = new Retrofit.Builder().baseUrl(NetConfig.BASE_LEFTCLASSIFT).build();
        mRetrofitInterface = mRetrofit.create(RetrofitInterface.class);
        mDecodeGoodsBase = new DecodeGoodsBase();

        gridViewAdapter = new GoodsGridViewAdapter(this, goodsDataList);
        mGridView.setAdapter(gridViewAdapter);
    }

    /**
     * 初始化View
     */
    private void initView() {
        mEditeTextSearchGift = (DrawableEditText) findViewById(R.id.editTextSearchGift);
        Drawable drawable = null;
        drawable = getResources().getDrawable(R.mipmap.ic_search);
        drawable.setBounds(0, 0, 40, 40);
        mEditeTextSearchGift.setCompoundDrawables(null, null, drawable, null);
        mTvCancel = (TextView) findViewById(R.id.textView_Cancel);
        mTvCancel.setOnClickListener(this);

        mGridView = (GridView) findViewById(R.id.goodsGridView);

        tvSynthesis = (TextView) findViewById(R.id.includeScreenHead).findViewById(R.id.textViewComprehensiveSort);
        tvPrice = (TextView) findViewById(R.id.textViewPriceSort).findViewById(R.id.textViewPriceSort);
        imgPriceSort = (ImageView) findViewById(R.id.includeScreenHead).findViewById(R.id.imageViewPriceRanklistSort);
        tvHot = (TextView) findViewById(R.id.includeScreenHead).findViewById(R.id.textViewHotSort);
        tvNew = (TextView) findViewById(R.id.includeScreenHead).findViewById(R.id.textViewNewSort);
        tvScreen = (TextView) findViewById(R.id.includeScreenHead).findViewById(R.id.textViewSortScreen);
        imgScreen = (ImageView) findViewById(R.id.includeScreenHead).findViewById(R.id.imageView_screen);

        tvSynthesis.setOnClickListener(this);
        tvPrice.setOnClickListener(this);
        tvHot.setOnClickListener(this);
        tvNew.setOnClickListener(this);
        tvScreen.setOnClickListener(this);
        int[] r = new int[]{R.id.viewHot1, R.id.viewHot2, R.id.viewHot3, R.id.viewHot4, R.id.viewHot5};
        for (int i = 0; i < views.length; i++) {
            views[i] = findViewById(R.id.includeScreenHead).findViewById(r[i]);
            views[i].setVisibility(View.INVISIBLE);
        }
        views[0].setVisibility(View.VISIBLE);
    }

    /**
     * 单击监听事件
     */
    @Override
    public void onClick(View v) {
        hindAllIndicating();
        goodsDataList.clear();
        switch (v.getId()) {
            case R.id.textView_Cancel:
                toastShow("取消");
                break;
            case R.id.textViewComprehensiveSort:
                imgPriceSort.setImageResource(R.mipmap.ic_price_sort_1);
                bastParameter();
                loadData();
                isLow2Height = false;
                views[0].setVisibility(View.VISIBLE);
                break;
            case R.id.textViewPriceSort://价格排序
                views[1].setVisibility(View.VISIBLE);
                gridViewAdapter.notifyDataSetChanged();
                if (!isLow2Height) {//从低价到高价
                    filter_type = 1;
                    loadData();
                    imgPriceSort.setImageResource(R.mipmap.ic_price_sort_2);
                    isLow2Height = true;
                } else {//从高价到低价
                    filter_type = 2;
                    loadData();
                    imgPriceSort.setImageResource(R.mipmap.ic_price_sort_3);
                    isLow2Height = false;
                }
                gridViewAdapter.notifyDataSetChanged();
                break;
            case R.id.textViewHotSort:
                isLow2Height = false;
                imgPriceSort.setImageResource(R.mipmap.ic_price_sort_1);
                views[2].setVisibility(View.VISIBLE);
                bastParameter();
                filter_type = 3;
                loadData();
                break;
            case R.id.textViewNewSort:
                isLow2Height = false;
                imgPriceSort.setImageResource(R.mipmap.ic_price_sort_1);
                views[3].setVisibility(View.VISIBLE);
                bastParameter();
                filter_type = 4;
                loadData();
                break;
            case R.id.textViewSortScreen:
                views[4].setVisibility(View.VISIBLE);
                showPop(tvScreen, 0, 0);
                break;
            case R.id.imageViewIsFreePost:
                if (!isFreePost) {//包邮逻辑
                    isFreePost = true;
                    imgIsFreePost.setImageResource(R.mipmap.ic_user_info_checked);
                    free_postage = 1;
                } else if (isFreePost) {//不包邮逻辑
                    isFreePost = false;
                    imgIsFreePost.setImageResource(R.mipmap.ic_user_info_check);
                    free_postage = 0;
                }
                break;
            case R.id.imageViewIsCurrHaveGoods:
                if (!isCurrHaveGoods) {//当地发货逻辑
                    isCurrHaveGoods = true;
                    imgIsCurrHaveGoods.setImageResource(R.mipmap.ic_user_info_checked);
                    is_stock = 1;
                } else if (isCurrHaveGoods) {//不指定位置发货
                    isCurrHaveGoods = false;
                    imgIsCurrHaveGoods.setImageResource(R.mipmap.ic_user_info_check);
                    is_stock = 0;
                }
                break;
            case R.id.buttonOver:
                popupWindow.dismiss();
                loadData();
                break;
        }
    }

    /**
     * Popuwindow
     */
    private void initPopuWindow() {
        View view = LayoutInflater.from(this).inflate(R.layout.screen_popuwindow_layout, null);
        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
//        popupWidow.setAnimationStyle(R.style.);
        imgIsFreePost = (ImageView) view.findViewById(R.id.imageViewIsFreePost);
        imgIsCurrHaveGoods = (ImageView) view.findViewById(R.id.imageViewIsCurrHaveGoods);
        rangeSeekBar = (RangeSeekBar) view.findViewById(R.id.rangeSeekBar);
        btnOver = (Button) view.findViewById(R.id.buttonOver);
        imgIsFreePost.setOnClickListener(this);
        imgIsCurrHaveGoods.setOnClickListener(this);
        btnOver.setOnClickListener(this);
    }

    /**
     * 显示Popuwindow
     */
    public void showPop(View parent, int x, int y) {
        //设置popwindow显示位置
        popupWindow.showAsDropDown(parent, x, y);
        //获取popwindow焦点
        popupWindow.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popupWindow.setOutsideTouchable(true);
        popupWindow.update();
    }


    /**
     * 加载数据
     */
    private void loadData() {
        loadBaseData(category, pager, free_postage, is_stock, filter_type, min_price, max_price);
    }

    /**
     * 恢复基本参数
     */
    private void bastParameter() {
        pager = 1;
        free_postage = 0;
        is_stock = 0;
        filter_type = 0;
        min_price = 0;
        max_price = -1;
    }

    /**
     * 隐藏指示条
     */
    private void hindAllIndicating() {
        for (int i = 0; i < views.length; i++) {
            views[i].setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 测试Toast
     *
     * @param s
     */
    private void toastShow(String s) {
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }
}
